package com.duang.framework.service;

import java.lang.reflect.Proxy;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

public class ServiceSingleFactory {

	private static Map<String, BaseService<?>> serviceMap;

	public static <T> T findServiceByClass(Class<T> clazz) {

		for (Entry<String, BaseService<?>> entry : serviceMap.entrySet()) {
			for (Class<?> interfaceClazz : entry.getValue().getClass()
					.getInterfaces()) {
				if (interfaceClazz.isAssignableFrom(clazz)) {
					return (T) entry.getValue();
				}
			}

		}
		return null;
	}

	public static BaseService<?> findServiceByName(String name) {
		if (serviceMap == null) {
			throw new NullPointerException(
					"null pointer exception!!!maybe services are not initialized");
		}
		return serviceMap.get(name);

	}

	public static void registerService(String name, BaseService<?> service,
			Map cacheMap) {
		registerService(name, service, cacheMap, true);
	}

	public static void registerService(String name, BaseService<?> service) {
		registerService(name, service, null, false);
	}

	public static void registerService(String name, BaseService<?> service,
			Map cacheMap, boolean useCache) {
		if (serviceMap == null)
			serviceMap = new HashMap<String, BaseService<?>>();
		TxManangerInterceptor interceptor = new TxManangerInterceptor(service,
				cacheMap, useCache);
		BaseService<?> serviceProxy = (BaseService<?>) Proxy.newProxyInstance(
				ServiceSingleFactory.class.getClassLoader(), service.getClass()
						.getInterfaces(), interceptor);
		serviceMap.put(name, serviceProxy);
	}
}
